<?php
/* [DoYouHaoBaby!] (C)Dianniu From 2010.
   this($)*/

!defined('DYHB_PATH') && exit;

class TemplateGtkWidgetCreator{

	protected $_arrWidgets=array();
	protected $_arrWidgetTree=array();
	protected $_arrWidgetIds=array();
	private $_arrObjectForSignal=array();
	protected $_sTemplatePath='';
	private $_oTemplate;
	const EXCE_ID_NOWIDGET=1;

	public function __construct(TemplateGtkGlade $oTemplate=null){
		$this->_oTemplate=$oTemplate;
	}

	public function getTemplate(){
		return $this->_oTemplate;
	}

	public function getSentence($sSentence){
		return $this->getTemplate()->getSentence($sSentence);
	}

	public function getWidget($sId,array $arrObjectForSignal=array()){
		if(class_exists('TemplateGtkGlade')){
			$sMethod='create_'.TemplateGtkGlade::getWidgetVariableName($sId);
		}
		else{
			$sMethod='create_'.str_replace('-','_',$sId);
		}
		$sTheId=TemplateGtkGlade::trimWidgetId($sId);
		if(!isset($this->_arrWidgets[$sTheId])){// 创建一个新的窗体
			$arrCallback=array($this,$sMethod);
			if(!is_callable($arrCallback,false)){
				G::E(G::L('Gtk Glade 模版文件“%s”中没有名为“%s”的窗体。','Dyhb',null,$this->getGladePath(),$sId));
			}
			$oNewIns=call_user_func_array($arrCallback, array($arrObjectForSignal));
			$oNewIns->connect_simple('destroy-event',array($this,'onDestroy'),$sTheId);
			$this->_arrWidgets[$sTheId]=$oNewIns;
		}
		return $this->_arrWidgets[$sTheId];// 返回享元对象
	}

	public function onDestroy($sWidgetId){
		unset($this->_arrWidgets[$sWidgetId]);
	}

	public function getWidgetTree(){
		return $this->_arrWidgetTree;
	}

	public function createWidgetIdIterator(){
		return new DArrayIterator($this->_arrWidgetIds);
	}

	public function getGladePath(){
		return $this->_sTemplatePath;
	}

	public function addObjectForSignal($sName,$oObject){
		A::STRING($sName);
		A::INSTANCE($oObject,'');
		$this->_arrObjectForSignal[$sName]=$oObject;
	}

	protected function connectSignal($sAction,$sObName,$sMethod,$bConnectSimple){
		$arrUserParams=func_get_args();
		array_shift($arrUserParams);// remove $sAction
		array_shift($arrUserParams);// remove $sObName
		array_shift($arrUserParams);// remove $sMethod
		array_shift($arrUserParams);// remove $bConnectSimple
		A::ASSERT_(isset($this->_arrObjectForSignal[$sObName]),G::L('名为 %s 的对象尚未设置','Dyhb',null,$sObName));
		$arrParams=array($sAction,array($this->_arrObjectForSignal[$sObName],$sMethod));
		$arrParams=array_merge($arrParams,$arrUserParams);
		call_user_func_array(array('Gtk',($bConnectSimple?'connect_simple':'connect')),$arrParams);
	}

}
